package cn.sc.summer.construction.sysimpl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import cn.sc.summer.constant.rabbit.RabbitConstant;
import cn.sc.summer.core.util.mail.EmailUtil;
import cn.sc.summer.exception.exceptions.CommonException;
import cn.sc.summer.rabbitmq.po.RabbitMessage;
import cn.sc.summer.rabbitmq.service.RabbitConsumerService;
import cn.sc.summer.rabbitmq.util.RabbitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 类名：rabbit消费异常达上限后处理实现类
 *
 * @author a-xin
 * @date 2023/9/26 10:54
 */
@Slf4j
@Service
public class RabbitErrorInfoServiceImpl extends RabbitConsumerService {

    /**
     * 接口: rabbit消费异常达上限后异步入库处理
     *
     * @param jsonStr 日志信息
     * @param message rabbit消息提
     * @param channel rabbit
     * @author a-xin
     * @date 2023/9/23 15:48
     */
    @RabbitListener(queues = RabbitConstant.ERROR_RECORD_QUEUE)
    public void consumer(String jsonStr, Message message, Channel channel) {
        try {
            log.error("==> Rabbit MQ: Receive an error message！");
            RabbitMessage<JSONObject> jsonObjectRabbitMessage = RabbitUtil.checkMessage(jsonStr, new TypeReference<JSONObject>() {});
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            if (jsonObjectRabbitMessage.getFlag()) {
                JSONObject jsonObject = jsonObjectRabbitMessage.getMessage();
                Map<String, String> data = new ConcurrentHashMap<>();
                data.put("错误信息", StrUtil.isBlank(jsonObject.getString("errorMessage")) ? "null" : jsonObject.getString("errorMessage"));
                data.put("参数信息", jsonObject.getString("params"));
                data.put("错误类型", jsonObject.getString("errorType"));
                data.put("错误类型描述", jsonObject.getString("errorDesc"));
                EmailUtil.sendEmail("RabbitMQ接收到错误消息报告", data);
            } else {
                log.error("==> 接收到重复消费消息：Queue: {}, Exchange : {}, RoutingKey : {}, Message : {}",
                        RabbitConstant.ERROR_RECORD_QUEUE,
                        RabbitConstant.ERROR_RECORD_EXCHANGE,
                        RabbitConstant.ERROR_RECORD_ROUTING_KEY,
                        jsonStr);
            }
        } catch (Exception e) {
            throw new CommonException(e.getMessage(), e);
        }
    }
}
